package com.timothy.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class MessageReceiveService  {
	public static final int MSG_REGISTER_CLIENT = 1;
	public static final int MSG_UNREGISTER_CLIENT = 2;
	public static final int MSG_QUESTION = 3;
    
	private static final int PORT = 9999;// 端口监听
	private static final String COMMAND_START = "<Message";
	private static final String COMMAND_END = "</Message>";
	
	
//    @Override
//    public IBinder onBind(Intent intent) {
//    	return rMessenger.getBinder();
//    }
//    
//    
//	@Override
//	public void onCreate() {
//		Thread receiveThread = new ReceiveThread();
//		receiveThread.start();
//	}
//	
//	public void ShowDialog(String msg) {
//		new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)
//				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) {
//					}
//				}).show();
//	}
//	
	private void processCommand(String command){
		Object obj = null;

	    String type = XMLUtil.getPropertyValue(command, "Type");
		if( "CommonQuestion".equals( type ) ) {
			int index = command.indexOf("<Content>")+"<Content>".length();
			int endIndex = command.indexOf("</Content>");
			
			String question = command.substring(index, endIndex);
			obj = QuestionBuilder.parseQuestion( question );
		}
			
	}
	 
	public class ReceiveThread extends Thread {
		//监听PC端消息
		public void run() {
			try {
				ServerSocket server = new ServerSocket(PORT);
				while (true) {
					Socket client = server.accept();
					BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
					StringBuffer commond = new StringBuffer();
					while (true) {
						String msg = in.readLine();
						if ( msg != null ) {
							msg = msg.trim();
							if( msg.startsWith( COMMAND_START ) )
								commond.setLength(0);
							else if( COMMAND_END.equalsIgnoreCase(msg) )
								break;
							else
								commond.append( msg );
						} else {
							break;
						}
					}
					in.close();
					client.close();
					
					processCommand( commond.toString() );
				}
			
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}		
	}
	
	public static void main(String[] args){
		String message = "<Message Type=\"CommonQuestion\">" +
		 "<Content>" +
		 "<Question Type=\"stTwoButtonAlpha\" SlideIndex=\"1\" QuestionName=\"a test\">" +
		 	"<Choice Index=\"1\" Text=\"True\"/>"+
		 	"<Choice Index=\"2\" Text=\"xxxx\"/>"+
		 	"</Question>" +       
		  "</Content>" +
		  "</Message>";
		
		MessageReceiveService mrs = new MessageReceiveService();
		mrs.processCommand(message);
	}
}
